// SPDX-License-Identifier: GPL-3.0-or-later

import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
import Qt5Compat.GraphicalEffects

import Fk
import Fk.Components.Common
import "./dashboard"
import Fk.Components.LunarLTK.Photo
import Fk.Widgets as W
import "../self" as QsgsSelf

MyPhotoBase {
  id: root
  frameVisible: false

  property string role: "unknown"
  property bool role_shown: false
  property bool role_visible: true
  property string netstate: "online"
  property int handcards: 0
  property int maxHp: 0
  property int hp: 0
  property int shield: 0
  property bool dying: false
  property bool faceup: true
  property bool chained: false
  property bool needHpBar: true
  property int drank: 0
  property int rest: 0
  property list<string> sealedSlots: []

  property int distance: -1
  property string status: "normal"
  property int maxCard: 0

  property alias equipArea: equipAreaItem
  property alias areasSealed: equipAreaItem
  property alias markArea: markAreaItem
  property alias specialArea: specialAreaItem
  property alias changeSkinTimer: cooldownTimer

  property bool doubleTapped: false

  property bool playing: false

  property var targetTip: []

  property color dominantKingdomColor: "#000000"
  property bool colorAnalysisCompleted: false

  /*
  PixmapAnimation {
    id: animSelectable
    source: SkinBank.pixAnimDir + "selectable"
    anchors.centerIn: parent
    loop: true
    visible: root.state === "candidate" && root.selectable
    running: visible
  }
  */

  Image {
    id: selfPhotoFrame
    source: {
      if (root.frameStyle) {
        return Cpp.path + "/packages/lunarltk-qsgs-ui/image/photo/frame/self/" + root.frameStyle + ".png"
      } else {
        return Cpp.path + "/packages/lunarltk-qsgs-ui/image/selfArea/self-photo-frame.png"
      }
    }
    anchors.fill: parent
    anchors.margins: 2
  }

  Image {
    id: turnedOver
    visible: !root.faceup
    source: Cpp.path + "/packages/lunarltk-qsgs-ui/image/photo/faceturned"
    anchors.fill: photoMask
  }

  Image {
    id: chain
    visible: root.chained
    source: Cpp.path + "/packages/lunarltk-qsgs-ui/image/photo/chain"
    anchors.horizontalCenter: parent.horizontalCenter
    y: 72
    width: root.width
  }

  Rectangle {
    id: nameBanner
    color: "transparent"
    width: parent.width
    height: 15
    visible: !root.isDeputy

    Glow {
      id: playerNameGlow
      source: playerName
      anchors.fill: playerName
      color: "gray"
      spread: 0.3
      radius: 4
    }

    Text {
      id: playerName
      anchors.centerIn: parent
      color: "white"

      font.pixelSize: 13
      text: {
        let ret = screenName;
        if (ret.length > 9)
        ret = ret.slice(0, 9) + "...";
        return ret;
      }
      elide: root.playerid === Self.id ? Text.ElideNone : Text.ElideMiddle
      horizontalAlignment: Qt.AlignHCenter
      style: Text.Outline
    }
  }

  Item {

    Image {
      id: kingdomFrame
      x: isDeputy ? -25 : -50
      y: 4
      width: 69
      height: 17
      source: {
        let ret = Cpp.path + "/packages/lunarltk-qsgs-ui/image/photo/kingdom/dashboard/" + root.kingdom + ".png";
        if (Backend.exists(ret)) return ret;
        return Cpp.path + "/packages/lunarltk-qsgs-ui/image/photo/kingdom/dashboard/qun";
      }
      onStatusChanged: {
        if (status === Image.Ready && 
            !Backend.exists(Cpp.path + "/packages/lunarltk-qsgs-ui/image/photo/kingdom/frame/" + root.kingdom + ".png") && 
            Backend.exists(SkinBank.getGeneralCardDir(root.kingdom) + root.kingdom + ".png")) {
          analyzeKingdomColor();
        }
      }
    }

    Colorize {
      id: kingdomColorize
      anchors.fill: kingdomFrame
      source: kingdomFrame
      saturation: 0.6
      lightness: 0.0
      hue: getHueFromColor(root.dominantKingdomColor)
      opacity: (!Backend.exists(Cpp.path + "/packages/lunarltk-qsgs-ui/image/photo/kingdom/frame/" + root.kingdom + ".png") && 
      Backend.exists(SkinBank.getGeneralCardDir(root.kingdom) + root.kingdom + ".png") && 
      root.colorAnalysisCompleted) ? 1 : 0
      Behavior on opacity { NumberAnimation { duration: 300 } }
    }

    Image {
      id: kingdomIcon
      anchors.left: kingdomFrame.left
      anchors.leftMargin: -2
      anchors.bottom: kingdomFrame.bottom
      anchors.bottomMargin: -2
      width: 22
      fillMode: Image.PreserveAspectFit
      visible: !root.isDeputy
      source: {
        let ret = Cpp.path + "/packages/lunarltk-qsgs-ui/image/photo/kingdom/icon/" + root.kingdom;
        if (Backend.exists(ret + ".png")) return ret;
        ret = SkinBank.getGeneralCardDir(root.kingdom) + root.kingdom
        if (Backend.exists(ret + ".png")) return ret;
        return Cpp.path + "/packages/lunarltk-qsgs-ui/image/photo/kingdom/icon/qun";
      }
      onStatusChanged: {
        if (status === Image.Ready && 
            !Backend.exists(Cpp.path + "/packages/lunarltk-qsgs-ui/image/photo/kingdom/frame/" + root.kingdom + ".png") && 
            Backend.exists(SkinBank.getGeneralCardDir(root.kingdom) + root.kingdom + ".png")) {
          analyzeKingdomColor();
        }
      }
    }

    Text {
      id: deputyIcon
      visible: root.isDeputy

      anchors.left: kingdomFrame.left
      anchors.leftMargin: -4
      anchors.bottom: kingdomFrame.bottom
      anchors.bottomMargin: 1
      font.family: "LiSu"
      font.pixelSize: 18
      font.bold: true

      color: "yellow"
      text: "副"
      textFormat: TextEdit.RichText
      style: Text.Outline // 摆烂一下
    }

    Canvas {
      id: colorAnalysisCanvas
      visible: false
      width: kingdomIcon.width
      height: kingdomIcon.height
      contextType: "2d"

      onPaint: {
      }
      onAvailableChanged: {
        if (available) {
          analyzeKingdomColor();
        }
      }
    }

    Text {
      id: generalName

      anchors.left: kingdomIcon.right
      anchors.leftMargin: -2
      width: 50
      // height: 63
      elide: Text.ElideNone
      wrapMode: Text.NoWrap
      anchors.bottom: kingdomFrame.bottom
      anchors.bottomMargin: font.pixelSize === 15 ? 2.5 : 3.5
      font.family: "LiSu"
      font.pixelSize: text.length > 3 ? (text.length > 5 ? 13 : 14) : 15
      font.bold: true
      // opacity: 0.9
      // horizontalAlignment: Text.AlignHCenter
      // lineHeight: 1.5
      // lineHeightMode: Text.FixedHeight
      color: "white"
      text: Lua.tr(root.general)
      textFormat: TextEdit.RichText
      style: Text.Outline // 摆烂一下

      // glow.color: "#3a3a3c"
      // glow.spread: 0.7
      // glow.radius: 3
      // glow.samples: 24
    }
  }


  Rectangle {
    anchors.fill: parent

    // visible: root.drank > 0
    color: "red"
    opacity: (root.drank <= 0 ? 0 : 0.4) + Math.log(root.drank) * 0.12
    Behavior on opacity { NumberAnimation { duration: 300 } }
  }

  QsgsSelf.HpBar {
    id: hp
    value: root.hp
    maxValue: root.maxHp
    shieldNum: root.shield
    anchors.bottom: parent.bottom
    anchors.bottomMargin: 2
    anchors.right: parent.right
    anchors.rightMargin: 2
    visible: root.needHpBar
  }

  ColumnLayout {
    id: restRect
    anchors.centerIn: photoMask
    anchors.leftMargin: 20
    visible: root.rest > 0

    GlowText {
      Layout.alignment: Qt.AlignCenter
      text: Lua.tr("resting...")
      font.family: Config.libianName
      font.pixelSize: 40
      font.bold: true
      color: "#FEF7D6"
      glow.color: "#845422"
      glow.spread: 0.8
    }

    GlowText {
      Layout.alignment: Qt.AlignCenter
      visible: root.rest > 0 && root.rest < 999
      text: root.rest
      font.family: Config.libianName
      font.pixelSize: 34
      font.bold: true
      color: "#DBCC69"
      glow.color: "#2E200F"
      glow.spread: 0.6
    }

    GlowText {
      Layout.alignment: Qt.AlignCenter
      visible: root.rest > 0 && root.rest < 999
      text: Lua.tr("rest round num")
      font.family: Config.libianName
      font.pixelSize: 28
      color: "#F0E5D6"
      glow.color: "#2E200F"
      glow.spread: 0.6
    }
  }

  /*
  Image {
    source: root.status != "normal" ? SkinBank.statusDir + root.status : ""
    x: -6
  }
  */

  MyEquipArea {
    id: equipAreaItem

    anchors.bottom: parent.bottom
    width: parent.width - hp.width
  }

  Item {
    id: specialAreaItem

    x: 31
    y: 139

    InvisibleCardArea {
      id: specialContainer
      // checkExisting: true
    }

    function updatePileInfo(areaName) {
      if (areaName.startsWith('#')) return;
      const data = Lua.call("GetPile", root.playerid, areaName);
      if (data.length === 0) {
        root.markArea.removeMark(areaName);
      } else {
        root.markArea.setMark(areaName, data.length.toString());
      }
    }

    function add(inputs, areaName) {
      updatePileInfo(areaName);
      specialContainer.add(inputs);
    }

    function remove(inputs, areaName) {
      updatePileInfo(areaName);
      return specialContainer.remove(inputs);
    }

    function updateCardPosition(a) {
      specialContainer.updateCardPosition(a);
    }
  }

  Image {
    // id: saveme
    visible: (root.dead && !root.rest) || root.dying || root.surrendered
    source: {
      if (root.surrendered) {
        return SkinBank.deathDir + "surrender";
      } else if (root.dead) {
        return SkinBank.getRoleDeathPic(root.role);
      }
      return Cpp.path + "/packages/lunarltk-qsgs-ui/image/photo/saveme.png";
    }
    anchors.centerIn: photoMask
    scale: (!root.dead && !root.surrendered && root.dying) ? 1.25 : 0.75
  }

  Image {
    id: netstat
    source: SkinBank.stateDir + root.netstate
    x: photoMask.x
    y: photoMask.y
    scale: 0.9
    transformOrigin: Item.TopLeft
  }


  Item {
    anchors.fill: parent
    visible: !root.isDeputy
    Image {
      id: handcardNum
      source: {
        let ret = Cpp.path + "/packages/lunarltk-qsgs-ui/image/photo/kingdom/handcard/" + root.kingdom + ".png";
        if (Backend.exists(ret)) return ret;
        return Cpp.path + "/packages/lunarltk-qsgs-ui/image/photo/kingdom/handcard/qun";
      }
      x: -6
      y: 83
      width: 27
      height: 16
    }

    Colorize {
      id: handcardColorize
      anchors.fill: handcardNum
      source: handcardNum
      saturation: 0.6
      lightness: 0.0
      hue: getHueFromColor(root.dominantKingdomColor)
      opacity: (!Backend.exists(Cpp.path + "/packages/lunarltk-qsgs-ui/image/photo/kingdom/handcard/" + root.kingdom + ".png") && 
      Backend.exists(SkinBank.getGeneralCardDir(root.kingdom) + root.kingdom + ".png") && 
      root.colorAnalysisCompleted) ? 1 : 0
      Behavior on opacity { NumberAnimation { duration: 300 } }
    }

    Text {
      text: {
        let n = root.handcards;
        n = Lua.call("GetPlayerHandcards", root.playerid).length;
        if (root.maxCard === root.hp || root.hp < 0) {
          return n;
        } else {
          const maxCard = root.maxCard < 900 ? root.maxCard : "∞";
          return n + "/" + maxCard;
        }
      }
      font.family: "Arial"
      font.pixelSize: (root.maxCard === root.hp || root.hp < 0 ) ? 14 : 14
      //font.weight: 30
      color: "white"
      anchors.centerIn: handcardNum
      style: Text.Outline
    }
  }

  onRightClicked: {
    showDetail();
  }

  RoleComboBox {
    id: role
    value: {
      if (root.role === "hidden") return "hidden";
      if (root.role_shown) return root.role;
      Lua.call("RoleVisibility", root.playerid) ? root.role : "unknown";
    }
    visible: root.role_visible
    anchors.top: parent.top
    anchors.topMargin: -4
    anchors.right: parent.right
    anchors.rightMargin: -4
  }

  LimitSkillArea {
    id: limitSkills
    anchors.top: parent.top
    anchors.right: parent.right
    anchors.topMargin: role.height + 2
    anchors.rightMargin: 30
  }

  OLMarkArea {
    id: markAreaItem
    visible: !((root.dead && !root.rest) || root.dying || root.surrendered)

    x: 18
    y: 18
    width: root.width - x
    height: root.height - y
  }

  Rectangle {
    opacity: (root.state === "candidate" && !selectable && !selected) ? 0.4 : 0
    anchors.fill: parent
    color: "black"
    Behavior on opacity {
      NumberAnimation { duration: 200 }
    }
  }

  Image {
    id: selectedBoarder
    source: Cpp.path + "/packages/lunarltk-qsgs-ui/image/photo/dashboardSelected"
    anchors.centerIn: parent
    width: parent.width - 2
    height: parent.height - 2
    // scale: 0.9
    visible: root.state === "candidate" && root.selected
  }

  SequentialAnimation {
    id: trembleAnimation
    running: false
    PropertyAnimation {
      target: root
      property: "x"
      to: root.x - 20
      easing.type: Easing.InQuad
      duration: 100
    }
    PropertyAnimation {
      target: root
      property: "x"
      to: root.x
      easing.type: Easing.OutQuad
      duration: 100
    }
  }

  function tremble() {
    trembleAnimation.start()
  }

  RowLayout {
    anchors.centerIn: parent
    spacing: 5

    Repeater {
      model: root.targetTip

      Item {
        // Layout.alignment: Qt.AlignHCenter
        width: modelData.type === "normal" ? 40 : 24

        GlowText {
          anchors.centerIn: parent
          visible: modelData.type === "normal"
          text: Util.processPrompt(modelData.content)
          font.family: Config.li2Name
          color: "#FEFE84"
          font.pixelSize: {
            if (text.length <= 3) return 36;
            else return 28;
          }
          //font.bold: true
          glow.color: "black"
          glow.spread: 0.3
          glow.radius: 5
          lineHeight: 0.85
          horizontalAlignment: Text.AlignHCenter
          wrapMode: Text.WrapAnywhere
          width: font.pixelSize + 4
        }

        Text {
          anchors.centerIn: parent
          visible: modelData.type === "warning"
          font.family: Config.libianName
          font.pixelSize: 24
          opacity: 0.9
          horizontalAlignment: Text.AlignHCenter
          lineHeight: 24
          lineHeightMode: Text.FixedHeight
          //color: "#EAC28A"
          color: "snow"
          width: 24
          wrapMode: Text.WrapAnywhere
          style: Text.Outline
          //styleColor: "#83231F"
          styleColor: "red"
          text: Util.processPrompt(modelData.content)
        }
      }
    }
  }

  InvisibleCardArea {
    id: defaultArea
    anchors.centerIn: parent
  }

  Rectangle {
    color: "white"
    height: 20
    width: 20
    visible: distance != -1
    Text {
      text: distance
      anchors.centerIn: parent
    }
  }

  Image {
    id: skinIcon
    width: 22
    height: 22
    anchors.right: parent.right
    anchors.top: parent.top
    anchors.rightMargin: 5
    anchors.topMargin: 20
    source: Cpp.path + "/packages/lunarltk-qsgs-ui/image/photo/skinoption.png"
    visible: false

    property bool hovered: false

    BrightnessContrast {
      anchors.fill: parent
      source: parent
      brightness: 0.3
      visible: parent.hovered
    }

    W.TapHandler {
      onTapped: {
        if (root.isDeputy) {
          roomScene.startCheat("SkinsDetail", {
          skins: [],
          deputy_skins: root.getSkinsByName(root.general),
          orig_general: "",
          orig_deputy: root.general
        });
        } else {
          roomScene.startCheat("SkinsDetail", {
          skins: root.getSkinsByName(root.general),
          deputy_skins: [],
          orig_general: root.general,
          orig_deputy: "",
        });
        }
      }
    }

    HoverHandler {
      cursorShape: Qt.PointingHandCursor
      onHoveredChanged: {
        if (hovered) {
          parent.hovered = true;
        } else {
          parent.hovered = false;
        }
      }
    }

    Timer {
      id: cooldownTimer
      interval: 5000
      running: false
    }
  }

  HoverHandler {
    id: hover
    onHoveredChanged: {
      if (hovered && !Config.observing && !cooldownTimer.running && (root.getSkinsByName(root.general).length > 0 || root.getSkinsByName(root.deputyGeneral).length > 0)) {
        skinIcon.visible = true;
      } else {
        skinIcon.visible = false;
      }
    }
  }

  function getSkinsByName(general) {
    let arr = Lua.evaluate(`(function()
      return Fk:getSkinsByGeneral("${general}") or {}
    end)()`);
    return arr
  }

  function updateLimitSkill(skill, time) {
    // limitSkills.update(skill, time);
  }

  function showDetail() {
    if (playerid === 0 || playerid === -1) {
      return;
    }

    roomScene.startCheat("PlayerDetail", { photo: this });
  }

  function analyzeKingdomColor() {
    if (kingdomIcon.status !== Image.Ready) return;
    if (!colorAnalysisCanvas.available) return;
    
    // 使用Canvas进行分析
    var ctx = colorAnalysisCanvas.getContext('2d');
    ctx.clearRect(0, 0, colorAnalysisCanvas.width, colorAnalysisCanvas.height);
    
    // 绘制图标到Canvas
    ctx.drawImage(kingdomIcon, 0, 0, colorAnalysisCanvas.width, colorAnalysisCanvas.height);
    
    // 获取图像数据
    var imageData = ctx.getImageData(0, 0, colorAnalysisCanvas.width, colorAnalysisCanvas.height);
    var data = imageData.data;
    
    // 存储非黑白颜色
    var colorMap = {};
    var totalPixels = 0;
    
    // 定义黑白阈值
    var blackThreshold = 30;    // RGB值都小于30认为是黑色
    var whiteThreshold = 220;   // RGB值都大于220认为是白色
    
    // 遍历所有像素
    for (var i = 0; i < data.length; i += 4) {
      var r = data[i];
      var g = data[i+1];
      var b = data[i+2];
      var a = data[i+3];
      
      // 跳过透明像素
      if (a < 128) continue;
      
      // 判断是否为黑白像素
      var isBlack = (r < blackThreshold && g < blackThreshold && b < blackThreshold);
      var isWhite = (r > whiteThreshold && g > whiteThreshold && b > whiteThreshold);
      
      // 如果不是黑白像素，则处理
      if (!isBlack && !isWhite) {
        // 将颜色量化到8级，减少颜色数量
        var quantizedR = Math.floor(r / 32) * 32;
        var quantizedG = Math.floor(g / 32) * 32;
        var quantizedB = Math.floor(b / 32) * 32;
        
        var colorKey = quantizedR + "," + quantizedG + "," + quantizedB;
        
        if (colorMap[colorKey]) {
          colorMap[colorKey].count++;
        } else {
          colorMap[colorKey] = {
            r: quantizedR,
            g: quantizedG,
            b: quantizedB,
            count: 1
          };
        }
        
        totalPixels++;
      }
    }
    
    // 转换为数组并排序
    var colorArray = [];
    for (var key in colorMap) {
      if (colorMap.hasOwnProperty(key)) {
        colorArray.push(colorMap[key]);
      }
    }
    
    // 按出现次数排序
    colorArray.sort(function(a, b) {
      return b.count - a.count;
    });
    
    // 取最主要的颜色
    if (colorArray.length > 0) {
      var dominantColor = colorArray[0];
      root.dominantKingdomColor = Qt.rgba(dominantColor.r / 255, dominantColor.g / 255, dominantColor.b / 255, 1);
      root.colorAnalysisCompleted = true;
    } else {
      root.colorAnalysisCompleted = false;
    }
  }
  
  // 从颜色获取色调值 (0.0-1.0)
  function getHueFromColor(color) {
    var r = color.r;
    var g = color.g;
    var b = color.b;
    
    var max = Math.max(r, g, b);
    var min = Math.min(r, g, b);
    var h;
    
    if (max === min) {
      h = 0; // 无色相 (灰度)
    } else {
      var d = max - min;
      switch (max) {
        case r: h = (g - b) / d + (g < b ? 6 : 0); break;
        case g: h = (b - r) / d + 2; break;
        case b: h = (r - g) / d + 4; break;
      }
      h /= 6;
    }
    
    return h;
  }

  // 当kingdom变化时重新分析颜色
  onKingdomChanged: {
    root.colorAnalysisCompleted = false;
    // 延迟一点时间确保新图标已加载
    analyzeTimer.restart();
  }

  Timer {
    id: analyzeTimer
    interval: 50
    onTriggered: {
      if (!Backend.exists(Cpp.path + "/packages/lunarltk-qsgs-ui/image/photo/kingdom/frame/" + root.kingdom + ".png") && 
          Backend.exists(SkinBank.getGeneralCardDir(root.kingdom) + root.kingdom + ".png")) {
        analyzeKingdomColor();
      }
    }
  }
}
